package com.specificgroup.jira.plugin.acpro.action;

import com.atlassian.plugin.webresource.WebResourceManager;
import com.specificgroup.jira.plugin.acpro.model.Settings;
import com.specificgroup.jira.plugin.acpro.service.AcproManager;
import com.specificgroup.jira.plugin.acpro.session.SessionUtil;
import com.specificgroup.jira.plugin.acpro.exception.AcproException;
import com.specificgroup.jira.plugin.acpro.Constants;
import com.specificgroup.jira.plugin.acpro.sync.Sync;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpSession;
import java.io.IOException;

import webwork.action.ServletActionContext;

/**
 * 
 * @author Ivan Holub
 */
public class ImportAction extends AcproActionSupport {

    private Logger log = Logger.getLogger(getClass());

    private static final String RESOURCE_KEY = "com.specificgroup.jira.plugin.acpro.jira-acpro-plugin:acpro-resource-js-import";

    private AcproManager acproManager;

    private WebResourceManager webResourceManager;

    public ImportAction(AcproManager acproManager, WebResourceManager webResourceManager) {
        this.acproManager = acproManager;
        this.webResourceManager = webResourceManager;
    }

    @Override
    protected String doExecute() throws Exception {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }

        webResourceManager.requireResource(RESOURCE_KEY);

        Settings settings = SessionUtil.getSettings();

        //remove objects from session
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.removeAttribute(Constants.SETTINGS_SESSION_KEY);
        session.removeAttribute(Constants.SESSION_TEMP_DATA_KEY);

        Sync sync = new Sync();
        session.setAttribute(Constants.SESSION_SYNC_KEY, sync);

        acproManager.startImport(sync, settings);

        return super.doExecute();
    }
}
